package controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import utils.PasswordEncrypt;

import model.Gebruiker;

import database.ReadDAO;

/**
 * Servlet implementation class InlogController
 */
public class InlogController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public InlogController() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String action = request.getParameter("action");
		if(action != null){
			if(action.equals("logout")){
				HttpSession session = request.getSession();
				session.invalidate();
				response.sendRedirect("./VeilingController");
			}
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		ReadDAO readdao = new ReadDAO();

		HttpSession session = request.getSession();
		String username = request.getParameter("inlognaam");
		String wachtwoord = request.getParameter("password");
		String encryptedpassword = "";

		try {
			encryptedpassword = PasswordEncrypt.getInstance().encrypt(wachtwoord);
		} catch (Exception e) {
			e.printStackTrace();
		}


		Gebruiker gebruiker = readdao.getGebruikerMetInlognaamEnWachtwoord(username, encryptedpassword);
		if(gebruiker != null){
			session.setAttribute("gebruiker", gebruiker);
			response.sendRedirect("./VeilingController");
		}else {
			request.setAttribute("Veilingen", readdao.getVeilingen());
			request.setAttribute("error", "badusernamepassword");
			RequestDispatcher view = request.getRequestDispatcher("/WEB-INF/errorpages/error.jsp");
			view.forward(request, response);
			return;
		}
	}
}
